package com.heima.search.service.impl;

import com.heima.common.search.ElasticSearchTemplate;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.SearchService;
import com.heima.search.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ElasticSearchTemplate elasticSearchTemplate;
    @Autowired
    private ApUserSearchService apUserSearchService;


    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {

        //提取入参
        int pageNum = dto.getPageNum();
        String searchWords = dto.getSearchWords();
        int pageSize = dto.getPageSize();
        Date minBehotTime = dto.getMinBehotTime();

        //关键字查询
        QueryStringQueryBuilder stringQueryBuilder = elasticSearchTemplate.getStringQueryBuilder(searchWords, Operator.OR, "title", "content");

        //时间范围查询
        Map<String, Object> conditionResult = new HashMap<>(1);
        //获取时间范围
        conditionResult.put("lt",minBehotTime.getTime());
        RangeQueryBuilder rangeQueryBuilder = elasticSearchTemplate.getRangeBuilder("publishTime", conditionResult);

        //布尔查询
        Map<String, AbstractQueryBuilder> boolCondition = new HashMap<>();
        boolCondition.put("must",stringQueryBuilder);
        boolCondition.put("filter", rangeQueryBuilder);
        BoolQueryBuilder boolQueryBuilder = elasticSearchTemplate.getBoolQueryBuilder(boolCondition);


        //高亮
        HighlightBuilder highlightBuilder = elasticSearchTemplate.getHighlightBuilder("title","<font style='color: yellow; font-size: inherit;'>", "</font>");

        //执行查询
        SearchResponse searchResout = elasticSearchTemplate.search("app_info_article", boolQueryBuilder, highlightBuilder, pageNum, pageSize, "publishTime", SortOrder.DESC);

      //保存查询记录
        Integer userId = AppThreadLocalUtil.getUser().getId();
        if (userId == null ){
            log.warn("id不能为空");
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        apUserSearchService.insert(searchWords,userId);

        //处理结果
        SearchHit[] hits = searchResout.getHits().getHits();
        List<Map<String , Object >> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                Text[] titles = highlightFields.get("title").getFragments();
                String join = StringUtils.join(titles, ",");
                sourceAsMap.put("h_title", join);
            } else {
                sourceAsMap.put("h_title", sourceAsMap.get("title"));
            }
            list.add(sourceAsMap);
        }



        return ResponseResult.okResult(list);
    }
}
